package cn.edu.dgut.css.sai.demo.remoteloadjar.remote;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.net.MalformedURLException;

/**
 * @author Sai
 * Created by Sai on 2020/6/8.
 */
@SpringBootApplication
public class RemoteJarServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(RemoteJarServerApplication.class, args);
    }

    // 方法一
    @Configuration
    static class MvcConfig implements WebMvcConfigurer {
        // http://localhost:9090/jar/remote-autoconfiguration.jar
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/jar/**").addResourceLocations("classpath:/jarFiles/");
        }
    }

    // 方法二
    @Controller
    static class JarFilesController {
        // http://192.168.1.105:9090/jar/remote-autoconfiguration.jar
        @GetMapping("/jar2/{jarFileName}")
        public ResponseEntity<Resource> getJarFile(@PathVariable String jarFileName) throws MalformedURLException {
            return ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .header(HttpHeaders.CONTENT_DISPOSITION,
                            "attachment; filename=\"" + jarFileName + "\"")
                    .body(new UrlResource("classpath:/jarFiles/" + jarFileName));
        }
    }

}
